package com.sc.nft.Handler;

import com.sc.nft.exception.GlobalException;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.exception.ModelException;
import com.sc.nft.sup.ErrorCode;
import com.sc.nft.sup.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import static com.sc.nft.sup.ErrorCode.CHECK_HOLD_COLLECTION;
import static com.sc.nft.sup.ErrorCode.CHECK_REGISTER_TIME;

@RestControllerAdvice(annotations = RestController.class)
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler({GlobalException.class})
    @ResponseBody
    public Result errorHandle(GlobalException e) {
        if (e.errorCode != null) {
            return Result.fail(e.errorCode);
        } else {
            return Result.fail(e.getMessage());

        }
    }

    @ExceptionHandler({ModelException.class})
    @ResponseBody
    public Result errorHandle(ModelException e) {
        return Result.fail(e.getErrorCode(), e.getData());
    }

    @ExceptionHandler({GlobalRunTimeException.class})
    @ResponseBody
    public Result errorHandle(GlobalRunTimeException e) {
        log.warn("业务异常：",e);
        if (e.errorCode != null) {
            if(e.errorCode.getMessage().equals(CHECK_REGISTER_TIME.getMessage()) ||
                    e.errorCode.getMessage().equals(CHECK_HOLD_COLLECTION.getMessage())){
            return Result.fail(e.errorCode,e.message);
            }
            return Result.fail(e.errorCode);
        } else {
            return Result.fail(e.getMessage());

        }
    }

    @ExceptionHandler({IllegalMonitorStateException.class})
    @ResponseBody
    public Result errorHandle(IllegalMonitorStateException e) {
        e.printStackTrace();
        return Result.fail("当前操作人数过多，请稍后再试");
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public Result errorHandle(MethodArgumentNotValidException e) {
        return Result.fail(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public Result errorHandle(Exception e) {
        e.printStackTrace();
        log.error("系统异常：", e);
        return Result.fail(ErrorCode.SYS_ERROR);
    }

}
